import { LoginUser } from "f2e-server3";
import createStore from "ipreact-for-react";

export interface IStoreState {
    loginUser?: LoginUser ;
    location_search: URLSearchParams;
}

const { connect, dispatch, getState } = createStore<IStoreState>([])({
    location_search: new URLSearchParams(window.location.search),
});

export { connect, dispatch, getState };

export const changeSearch = (values: Record<string, string>, title: string = '') => {
    const { location_search } = getState();
    for (const [key, value] of Object.entries(values)) {
        if (!value) {
            location_search.delete(key);
        } else {
            location_search.set(key, value);
        }
    }
    history.pushState(null, title, `?${location_search.toString()}`);
    dispatch(state => {
        return {
            ...state,
            location_search: new URLSearchParams(location_search),
        };
    });
}

addEventListener('popstate', () => {
    dispatch(state => {
        return {
            ...state,
            location_search: new URLSearchParams(window.location.search),
        };
    });
})